# -*- coding: utf-8 -*-
'''
   Copyright (c) 2021 FromVB2Python
   FromVB2Python is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details.  
'''
import random
import tkinter as tk

def generate():
    '''生成符串'''
    n = 30
    chrs ='abcABC' 
    s =''.join([random.choice(chrs) for i in range(n)])
    txt1.delete(0, 'end')  # 清空txt1中的内容 
    lbx.delete(0, 'end')  # 清空lbx中的内容
    txt2.delete(0, 'end')  # 清空txt2中的内容  
    txt1.insert(0, s)  # 把字符串插入txt1中

def remove():
    '''消除'''
    lbx.delete(0, 'end')  # 清空lbx中的内容
    txt2.delete(0, 'end')  # 清空txt2中的内容 
    i = 0
    m = 1
    s = txt1.get()  # 获取txt1中的字符串
    while i<len(s)-1:
        k = i
        while isSame(s[i],s[i+1]):
            i += 1
            if i == len(s) -1:
                break

        if i - k >= 2:
            b = s[k:i+1]
            s = s[:k] + s[i+1:]
            # 输出到lbx
            lbx.insert('end','第{}次消除的字符：{}'.format(m,''.join(b)))
            m += 1            
            i = k - 3
            if i<-1: i=-1
        i += 1
    # 输出结果串到txt2
    txt2.insert(0,s)

def isSame(a1, a2):
    '''判断2个字符的值是否相等（不区分大小写）'''
    return a1.upper() == a2.upper()

# 创建界面及组件
win = tk.Tk()
win.title('消除字符')
win.resizable(0, 0)
btn1 = tk.Button(win, text='生成字符串', command=generate)
btn2 = tk.Button(win, text='消除',command=remove)
lbl1 = tk.Label(win, text='消除过程')
lbl2 = tk.Label(win, text='消除后的字符串：')
txt1 = tk.Entry(win, width=40)
txt1.insert(0, 'BCcbbaaabAbAaaA')
lbx = tk.Listbox(win, width=40, height=5)
txt2 = tk.Entry(win, width=40)
btn1.grid(row=0, column=0)
txt1.grid(row=0, column=1)
lbl1.grid(row=1, column=1, sticky='w')
btn2.grid(row=2, column=0)
lbx.grid(row=2, column=1)
lbl2.grid(row=3, column=0)
txt2.grid(row=3, column=1, pady=10, padx=10)
win.mainloop()
